<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { GoodsInfoResult, AuthorPriceData } from '@/api/details/types'
import APIDetails from '@/api/details'

const dialogVisible = shallowRef(false)
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const goodsInfo = inject<Ref<GoodsInfoResult>>('goodsInfo')

watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
}, { immediate: true })


const list = ref<any>([])

function getAuthorPrice() {
    if (!goodsInfo?.value.goods_id) return
    const data: AuthorPriceData = {
        type: 'music',
        goods_id: goodsInfo?.value.goods_id
    }
    APIDetails.getAuthorPrice(data).then(({ data }) => {
        list.value = data
    })
}

watch(dialogVisible, (newValue) => {
    if (newValue) {
        getAuthorPrice()
        getWallet()
    }
    $emit('update:modelValue', newValue)
})

function onBeforeClose() {
    dialogVisible.value = false
}
watch(list, (newValue) => {
    if (newValue.length != 0) {
        activeAuthType.value = newValue[0].auth_type
    }
}, { deep: true })


const activeAuthType = shallowRef<string>('')

const activeList = computed(() => {
    if (list.value.length != 0) {
        const data = list.value.filter((item: any) => item.auth_type == activeAuthType.value)
        if (data.length != 0) {
            return data[0]
        }
    }
    return {}
})

/** 加入购物车 */
function handleAddToShoppingCart() {
    ElMessageBox.confirm(
        '是否加入购物车？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const data: any = {
            id: (goodsInfo?.value.id as number),
            title: (goodsInfo?.value.title as string),
            price: (activeList.value.get_price),
            auth_detail: (activeList.value.auth_detail),
            image: (goodsInfo?.value?.image as string),
            type: 'music',
            auth_type: activeAuthType.value,
            market_price: activeList.value?.market_price,
            get_price: activeList.value?.get_price,
            total_amount: activeList.value?.get_price,
            using_body: activeList.value?.using_body
        }
        const loading = ElLoading.service({ lock: true })
        APIDetails.setShopCart(data).then(() => {
            ElMessage({
                message: '已加入购物车',
                type: 'success',
                offset: 80
            })
            onBeforeClose()
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

const innerVisible = shallowRef<any>(false)
function onInnerClose() {
    innerVisible.value = false
}

function handlePurchase() {
    innerVisible.value = true
}

const walletNumber = shallowRef<number>(0)
function getWallet() {
    APIDetails.getWallet().then(({ data }) => {
        walletNumber.value = data.Wallet
    })
}

const confirmed = shallowRef<any>()

function submitPay() {
    if (!confirmed.value) return ElMessage.error('请先勾选确认订单信息，并认可《心安元素授权服务协议》及《产品退款规则》')

    const formData: any = {
        id: goodsInfo?.value.id,
        goods_id: goodsInfo?.value.goods_id,
        type: goodsInfo?.value.type,
        auth_type: activeAuthType.value,
        auth_detail: activeList.value?.auth_detail,
        market_price: activeList.value?.market_price,
        get_price: activeList.value?.get_price,
        total_amount: activeList.value?.get_price,
        using_body: activeList.value?.using_body
    }
    const loading = ElLoading.service({ lock: true })
    APIDetails.setOrder(formData).then(() => {
        ElMessage.success('支付成功')
        onBeforeClose()
    }).finally(() => {
        loading.close()
    })
}

function handleJumpWallet() {
    window.location.href = `${import.meta.env.VITE_APP_CONSOLE_URL}/wallet`
}

</script>

<template>
    <el-dialog class="purchase-product" v-model="dialogVisible" width="850" destroy-on-close
        :before-close="onBeforeClose" :show-close="false">
        <template #header>
            <DialogClose title="请选择您购买的产品授权" @close="onBeforeClose" />
        </template>
        <el-dialog class="upload-blockchain" v-model="innerVisible" width="1000" destroy-on-close
            :before-close="onInnerClose" :show-close="false">
            <template #header>
                <DialogClose title="支付" @close="onInnerClose" />
            </template>
            <div>
                <div class="upload-blockchain-top">
                    <div class="video">
                        <div v-if="goodsInfo?.type == 'video'">
                            <video v-if="goodsInfo?.sample" controls :src="goodsInfo.sample"></video>
                        </div>
                        <div v-if="goodsInfo?.type != 'video'">
                            <img v-if="goodsInfo?.image" :src="goodsInfo.image" alt="image">
                        </div>
                    </div>
                    <div class="video-info">
                        <div class="video-info-title">
                            产品信息：
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">名 字：</span>{{ goodsInfo?.title }}
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">类 型：</span><span v-if="goodsInfo?.type == 'video'">视频素材</span>
                            <span v-if="goodsInfo?.type == 'picture'">图片素材</span>
                            <span v-if="goodsInfo?.type == 'music'">音乐素材</span>
                            <span v-if="goodsInfo?.type == 'font'">字体素材</span>
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">编 号：</span>{{ goodsInfo?.code }}
                        </div>
                        <div class="video-info-title">
                            授权信息：
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">授权类型：</span>{{ activeAuthType }}
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">授权详情信息：</span>{{ activeList?.auth_detail }}
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">价格：</span>{{ activeList?.get_price }}
                        </div>
                        <div class="video-info-item">
                            <span style="font-family: 'SOURCEHANSANSCN-LIGHT';">市场价：{{ activeList?.market_price }}</span>
                        </div>
                    </div>
                </div>

                <div class="upload-blockchain-money">
                    <div></div>
                    <div>本订单才有余额抵扣（当前账户余额 <span>￥{{ walletNumber }}</span> 元）
                        请保证有足够的余额，余额不够时，请点击“<span @click="handleJumpWallet">充值</span>”来增加余额）</div>
                </div>
                <div class="upload-blockchain-sum">
                    <div>应付金额：</div>
                    <div>￥{{ activeList?.get_price }}</div>
                </div>
                <div class="upload-blockchain-affirm">
                    <el-radio :value="true" size="large" v-model="confirmed" text-color="#606266">
                        <div style="color: #606266; font-family: 'SOURCEHANSANSCN-LIGHT';">确认订单信息，并认可<span
                                class="active">《心安元素授权服务协议》</span>及<span class="active">《产品退款规则》</span></div>
                    </el-radio>
                </div>
                <div class="upload-blockchain-btn">
                    <button @click="submitPay">支付</button>
                </div>
            </div>

        </el-dialog>

        <div class="item">
            <div class="item-title">授权类型：</div>
            <div class="item-box">
                <div class="item-box-content" :class="{ 'item-box-content-active': item.auth_type == activeAuthType }"
                    v-for="item in list" :key="item" @click="activeAuthType = item.auth_type">{{ item.auth_type }}</div>
            </div>
        </div>
        <div class="item">
            <div class="item-title">授权详情信息：</div>
            <div class="item-text" v-if="activeList?.auth_detail">{{ activeList?.auth_detail }}</div>
        </div>
        <div class="item">
            <div class="item-money-1">
                价格：<span><span>￥{{ activeList?.get_price || 0 }}元</span></span>
            </div>
            <div class="item-money-2">
                市场价：<span>￥{{ activeList?.market_price || 0 }}</span>
            </div>
        </div>
        <div class="submit-btns">
            <button type="button" @click="handleAddToShoppingCart">加入购物车</button>
            <button type="button" @click="handlePurchase">立即购买</button>
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.upload-blockchain {
    .upload-blockchain-btn {
        display: flex;

        button {
            width: 176px;
            height: 50px;
            border-radius: 5px;
            background-color: rgba(249, 20, 20, 1);
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            text-align: center;
            border: none;
            cursor: pointer;
            margin-left: auto;
            margin-right: 42px;
        }
    }

    .upload-blockchain-affirm {
        display: flex;
        justify-content: flex-end;
        margin-right: 42px;

        .active {
            color: #3894FF;
        }
    }

    .upload-blockchain-sum {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        margin-right: 42px;
        margin-top: 10px;

        div {
            &:nth-child(1) {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
            }

            &:nth-child(2) {
                color: rgba(249, 20, 20, 1);
                font-size: 36px;
                line-height: 1em;
                font-weight: 700;
            }
        }
    }

    .upload-blockchain-money {
        display: flex;
        justify-content: center;
        gap: 0 16px;
        margin-top: 56px;
        font-family: 'SOURCEHANSANSCN-LIGHT';

        div {
            &:nth-child(1) {
                width: 4px;
                height: 50px;
                background-color: #FF0000;
            }

            &:nth-child(2) {
                width: 860px;
                height: 50px;
                line-height: 50px;
                border-radius: 5px;
                background-color: rgba(238, 238, 239, 1);
                border: 1px dashed rgba(187, 187, 187, 1);
                font-size: 14px;
                color: #3894FF;
                text-align: center;

                span {
                    color: #F91414;
                    cursor: pointer;
                }
            }
        }
    }

    .upload-blockchain-top {
        display: flex;
        gap: 0 44px;

        .video-info {
            color: rgba(16, 16, 16, 1);

            .video-info-title {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                display: flex;
                align-items: center;
                line-height: 20px;
                margin-bottom: 10px;
                font-family: 'SOURCEHANSANSCN-REGULAR';

                &::before {
                    content: '';
                    display: block;
                    width: 3px;
                    height: 14px;
                    background-color: #FF0000;
                    margin-right: 8px;
                }
            }

            .video-info-item {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                margin: 10px 0;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }

        .video {
            width: 256px;
            height: 256px;
            background-color: #eeeeee;
            display: flex;
            align-items: center;

            div {
                video {
                    width: 100%;
                    height: 143px;
                    object-fit: cover;
                }

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }


        }
    }

}

.purchase-product {

    .submit-btns {
        display: flex;
        justify-content: flex-end;
        gap: 0 15px;

        button {
            width: 130px;
            height: 45px;
            display: block;
            border: none;
            border-radius: 5px;
            color: #ffffff;
            cursor: pointer;
            font-family: 'SOURCEHANSANSCN-LIGHT';
            font-size: 16px;

            &:nth-child(1) {
                background-color: #EC6A2B;
            }

            &:nth-child(2) {
                background-color: #F91414;
            }
        }
    }

    .item {
        margin-bottom: 30px;

        .item-text {
            box-sizing: border-box;
            border: 1px solid #BBBBBB;
            border-radius: 5px;
            padding: 6px 15px;
        }

        .item-box {
            display: grid;
            grid-template-columns: repeat(4, 190px);
            justify-content: space-between;
            gap: 16px 0;
            margin-top: 15px;


            .item-box-content {
                height: 35px;
                border-radius: 5px;
                border: 1px solid #BBBBBB;
                font-size: 14px;
                color: #101010;
                text-align: center;
                line-height: 35px;
                cursor: pointer;
                user-select: none;
            }

            .item-box-content-active {
                border-color: #F91414;
                background-color: #F91414;
                color: #ffffff;
            }
        }

        .item-title {
            font-size: 18px;
            color: #101010;
            font-family: 'SOURCEHANSANSCN-REGULAR';
        }

        .item-money-1 {
            font-size: 16px;
            color: #101010;
            margin-top: 45px;
            font-family: 'SOURCEHANSANSCN-LIGHT';

            span {
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

                span {
                    color: #F91414;
                }
            }
        }

        .item-money-2 {
            color: #101010;
            text-decoration: line-through;
            font-family: 'SOURCEHANSANSCN-LIGHT';

            span {
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }
    }



}
</style>
